package com.example.client_anna.module.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.client_anna.R;
import com.example.client_anna.util.adapter.ExploreAdapter;
import com.example.client_anna.network.okhttp3.HttpUtilImpl;
import com.example.client_anna.util.entity.Explore_data;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
public class ExploreFragment extends Fragment implements View.OnClickListener {

    public static final String TAG = "ExploreFragment";

    private BottomSheetDialog bottomSheetDialog;
    private List<Explore_data> explore_data_new = new ArrayList<>();
    private List<Explore_data> explore_data_filter = new ArrayList<>();
    private List<Explore_data> explore_data_add = new ArrayList<>();
    private List<Explore_data> explore_data_show = new ArrayList<>();
    private RecyclerView recyclerView;
    private ExploreAdapter exploreAdapter;
    private View rootView;
    private boolean aBoolean = false;

    /*-----------------------------------UI界面请求数据---------------------------------------------*/
    private void Explore_Okhttp3(String demand){
        //链接的地址
        String address = RequestUrl.getUrl()+"explore";
        //创建RequestBody请求体,用于数据的提交
        RequestBody requestBody = new FormBody.Builder()
                .add("id","001")
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 4;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String responseData=response.body().string();
                //分析返回的数据
                ParesJsonWithGSON(responseData,demand);

            }
        });
    }
    //采用GSON分析方式进行数据的转换
    private void ParesJsonWithGSON(String jsonData,String demand){

        if(jsonData!=null&&!jsonData.isEmpty()) {

            Gson gson = new Gson();

            //转换json数组，使用List<Explore_data>接收
            //最新请求的数据
            explore_data_new = gson.fromJson(jsonData, new TypeToken<List<Explore_data>>(){
            }.getType());

            //控制台显示最新请求的数据
            for (Explore_data i : explore_data_new) {
                Log.d(TAG, "new_id is " + i.getExploreid());
            }

            Duplicate_data(demand);

        }
    }
    /*------------------------------------数据筛选-------------------------------------------------*/
    private int n;
    public void Duplicate_data(String demand){

        //Load表示此次请求的数据用于加载更多
        if("Load".equals(demand)){
            //上拉加载状态aBoolean为false表示启用，才进行数据的加载
            //在explore_data_add.size()的为0的时候aBoolen为true，表示需要禁用上拉加载
            //每次发起上拉加载请求，explore_data_add从新申请的explore_data_new数据集中获取不重复的数据
            //explore_data_add.size()最大为8条数据，也就是一次最多加载8条数据
           if(aBoolean==false) {

               explore_data_add.clear();
               //对list数据集进行遍历
               for (Explore_data i : explore_data_new) {

                   n = Storing_data(demand, i.getExploreid());
                   if (n == 1) {
                       explore_data_add.add(i);
                   }

                   //最多一次加载8条数据
                   if (explore_data_add.size() == 8) {
                       break;
                   }

               }

               for (int i = 0; i < 20; i++) {
                   Log.d(TAG, "redata    " + redata[i]);
               }

               for (Explore_data i : explore_data_add) {
                   Log.d(TAG, "add_id is " + i.getExploreid());
               }

               if (explore_data_add.size() >= 1) {
                   //上拉加载_请求的数据explore_data_add为最新需要填充的数据
                   Message message = new Message();
                   message.what = 2;
                   handler.sendMessage(message);
               } else {
                   //上拉加载，explore_data_add填充的数据为空，表示没有数据
                   //把aBoolean设为true，表示禁用
                   Message message = new Message();
                   message.what = 3;
                   handler.sendMessage(message);
               }
           }else {
               //什么都不做
           }

        }else {
            //第一次绘制和刷新显示的数据
            explore_data_filter.clear();
            for (int i=0;i<8;i++) {
                explore_data_filter.add(explore_data_new.get(i));
            }
            //每次刷新的数据集都需要清空一下，再从新加载数据
            explore_data_show.clear();
            //刷新清空记录是否是重复数据的数组redata[]
            for (int i=0;i<100;i++){
                redata[i]="";
            }
            //redata[]的数组下标从0从新开始加载数据
            num=0;
            length=1;
            //对list数据集进行遍历
            for(Explore_data i:explore_data_filter){

                //调用Storing_data方法对新申请的数据进行筛选，去除重复的数据
                int n=Storing_data("draw",i.getExploreid());
                //n==1,表示该条数据不重复，需要进行加载
                if(n==1){
                    explore_data_show.add(i);
                }

            }

            //第一次绘制和下拉刷新_请求的数据explore_data_show为需要显示的数据
            Message message = new Message();
            message.what=1;
            handler.sendMessage(message);
        }

    }

    private String[] redata = new String[100];
    private int length;
    private int num;

    //声明一个String[] redata数组用于存储每次加载的id值
    //每次加载申请的数据与数组中的id进行对比，不相同就添加进数组
    //并且返回int 1 表示该条数据需要显示在UI界面上
    public int Storing_data(String demand,String dataid){

        //Load表示上拉加载对数组redata进行添加
        //其他表示刷新和第一次绘制，对redata[]数组进行初始化
        if("Load".equals(demand)){
            //加载判断是否重复数据
            //判断两个字符串是否相等不能使用==,要使用.equals方法
            for (int i=0;i<length;i++){
                Log.d(TAG,"加载执行次数"+i);
                if(!(dataid.equals(redata[i]))) {
                    if(i==length-1){
                        redata[num++] = dataid;
                        length++;
                        //不重复
                        return 1;
                    }
                }else {
                    //重复
                    return 2;
                }
            }

        }else {
            //判断两个字符串是否相等不能使用==,要使用.equals方法
            for (int i=0;i<length;i++){
                Log.d(TAG,"刷新执行次数"+i);
                if(!(dataid.equals(redata[i]))) {
                    if(i==length-1){
                        //刷新存储redata初始值
                        redata[num]=dataid;
                        //下一次存储不重复数据的数组下标，顺序存储
                        num++;
                        //不重复数据的数量
                        length++;
                        return 1;
                    }
                }else {
                    //重复
                    return 2;
                }
            }

        }

        return 0;
    }

    /*-----------------------------------更新UI界面------------------------------------------------*/
    public Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    exploreAdapter = new ExploreAdapter(explore_data_show);
                    //加载闪烁问题：添加标记tag,tag标记着每一张请求url的图片，加载的时候防止重新加载
                    //需要重写adapter的getItemId方法
                    exploreAdapter.setHasStableIds(true);
                    //适配器数据改变
                    exploreAdapter.notifyDataSetChanged();
                    //GridLayoutManager布局方式，参数1:Context，参数2:列数
                    GridLayoutManager layoutManager = new GridLayoutManager(getContext(),2);
                    //加载布局方式
                    recyclerView.setLayoutManager(layoutManager);
                    //recyclerView布局加载适配器
                    recyclerView.setAdapter(exploreAdapter);
                    break;
                case 2:
                    //上拉加载填充数据
                    //调用适配器中的addLoadItemf()方法对数据进行填充
                    exploreAdapter.addLoadItem(explore_data_add);
                    //适配器数据改变
                    exploreAdapter.notifyDataSetChanged();
                    break;
                case 3:
                    //参数1：在哪显示，参数2：显示什么，参数3：显示的时间
                    Toast.makeText(getActivity(),"没有数据了",Toast.LENGTH_SHORT).show();
                    //设置上拉加载的状态aBoolean为true表示需要禁用上拉加载
                    aBoolean=true;
                    break;
                case 4:
                    //请求服务器数据失败
                    Toast.makeText(getActivity(),"网络出错，请等待！",Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    //底部弹窗
                    BottomPopup_Show();
                    break;
                case 6:
                    //底部弹窗显示选择的图片
                    if(explore_bitmap==null){
                        Toast.makeText(getActivity(),"图片显示异常，请稍后再试！",Toast.LENGTH_SHORT).show();
                    }else {
                        explore_image_text.setText("");
                        Glide.with(getContext()).load(explore_bitmap).into(explore_pic);
                    }
                    break;
                case 7:
                    if("".equals(text_theme.getText().toString())){
                        Toast.makeText(getActivity(),"主题不能为空",Toast.LENGTH_SHORT).show();
                    }else if("".equals(text_story.getText().toString())){
                        Toast.makeText(getActivity(),"详细内容不能为空",Toast.LENGTH_SHORT).show();
                    }else if(file==null){
                        Toast.makeText(getActivity(),"请选择需要上传的图片",Toast.LENGTH_SHORT).show();
                    }else {
                        Bottom_Okhttp3();
                    }
                    break;
                case 8:
                    Toast.makeText(getActivity(),"添加成功",Toast.LENGTH_SHORT).show();
                    bottomSheetDialog.dismiss();
                    break;
                case 9:
                    Toast.makeText(getActivity(),"服务器异常，添加失败",Toast.LENGTH_SHORT).show();
                    break;
                case 10:
                    Toast.makeText(getActivity(),"该图片路径访问失败，请重新选择",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    /*-----------------------------------底部弹窗界面------------------------------------------------*/
    //图片按钮
    private ImageView explore_photo;
    //图片显示
    private ImageView explore_pic;

    private TextView explore_image_text;
    private EditText text_theme;
    private EditText text_detail;
    private EditText text_story;
    private ImageView imageView_theme;
    private ImageView imageView_detail;
    private ImageView imageView_story;

    private ImageView imageView_submit;

    //登录用户的信息
    private String user_id;

    //底部弹窗显示
    public void BottomPopup_Show (){
        //实例化BottomSheetDialog
        //参数1：当前context 参数2：背景透明化
        bottomSheetDialog = new BottomSheetDialog(getActivity(),R.style.BottomSheetDialog);
        View view = getLayoutInflater().inflate(R.layout.explore_dialog_bottom,null);

        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.show();

        explore_photo = view.findViewById(R.id.explore_photo);
        explore_pic = view.findViewById(R.id.explore_pic);
        explore_image_text = view.findViewById(R.id.explore_image_txt);
        explore_photo.setOnClickListener(this);

        text_theme = view.findViewById(R.id.bottom_theme);
        text_detail = view.findViewById(R.id.bottom_detail);
        text_story = view.findViewById(R.id.bottom_story);

        imageView_theme = view.findViewById(R.id.theme_but);
        imageView_detail = view.findViewById(R.id.detail_but);
        imageView_story = view.findViewById(R.id.story_but);
        imageView_theme.setOnClickListener(this);
        imageView_detail.setOnClickListener(this);
        imageView_story.setOnClickListener(this);

        imageView_submit = view.findViewById(R.id.bottom_submit);
        imageView_submit.setOnClickListener(this);

        //获取登录用户的信息
        //访问存储在本地的文件，通过键值对的方式读取想要的信息出来
        SharedPreferences preferences = getActivity().getSharedPreferences("UserInfo",
                Context.MODE_PRIVATE);
        user_id = preferences.getString("user_id","");

    }
    /*--------------------------------底部弹窗添加分享信息-------------------------------------------*/
    private void Bottom_Okhttp3(){
        Log.d(TAG,"bottom "+user_id);
        Log.d(TAG,"bottom "+text_theme.getText().toString());
        Log.d(TAG,"bottom "+text_detail.getText().toString());
        Log.d(TAG,"bottom "+text_story.getText().toString());
        Log.d(TAG,"bottom "+file.toString());
        //链接的地址
        String address = RequestUrl.getUrl()+"explore";
        //创建RequestBody请求体,用于数据的提交
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("id","004")
                .addFormDataPart("userid",user_id)
                .addFormDataPart("theme",text_theme.getText().toString().trim())
                .addFormDataPart("detail",text_detail.getText().toString().trim())
                .addFormDataPart("story",text_story.getText().toString().trim())
                .addFormDataPart("file","explore"+"_"+
                                System.currentTimeMillis()+".jpg",
                        RequestBody.create(MediaType.parse("image/png"),file))
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 4;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String Data_bottom=response.body().string();
                //分析返回的数据
                ParesJsonWithGSON_Bottom(Data_bottom);

            }
        });
    }

    private void ParesJsonWithGSON_Bottom(String data){

        if(data!=null&&!data.isEmpty()) {

            Gson gson = new Gson();
            Map<String,String> map = gson.fromJson(data,new TypeToken<Map<String,String>>()
            {}.getType());

            if("添加成功".equals(map.get("back_info"))) {
                Message message = new Message();
                message.what = 8;
                handler.sendMessage(message);
            }else {
                Message message = new Message();
                message.what = 9;
                handler.sendMessage(message);
            }
        }

    }
    
    /*----------------------------从手机相册选择图片或者拍照上传---------------------------------------*/
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.explore_photo:
                final String[] item = {"相册","拍照"};
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("请选择获取图片的方式：");
                builder.setItems(item, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case 0:
                                //相册
                                //动态申请WRITE_EXTERNAL_STORAGE权限，用来获取图片
                                if(ContextCompat.checkSelfPermission(getActivity(),
                                        Manifest.permission.
                                        WRITE_EXTERNAL_STORAGE) != PackageManager.
                                        PERMISSION_GRANTED){
                                    //申请权限
                                    ActivityCompat.requestPermissions(getActivity(),
                                            new String[]{
                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                    Manifest.permission.READ_EXTERNAL_STORAGE
                                            }
                                            ,1);
                                }else {
                                    //用户成功授权访问相册后，调用该方法获取图片
                                    go_album();
                                }
                                break;
                            case 1:
                                //拍照
                                go_graph();
                                break;
                        }
                    }
                });
                builder.create().show();
                break;
            case R.id.theme_but:
                text_theme.setText("");
                break;
            case R.id.detail_but:
                text_detail.setText("");
                break;
            case R.id.story_but:
                text_story.setText("");
                break;
            case R.id.bottom_submit:
                Message message = new Message();
                message.what = 7;
                handler.sendMessage(message);
                break;
        }
    }

    public static final int CHOOSE_PHOTO = 1;
    //从相册获取图片
    private void go_album(){
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);
    }

    public static final int TAK_PHOTO = 2;
    //Uri:Android开发使用，扩展了JAVA中URL的一些功能来特定的适用于Android开发
    private Uri imageUri;
    private File outputImage;
    //拍照获取图片
    private void go_graph(){

        //创建一个file文件，并且存放在应用关联缓存目录中
        //应用关联缓存目录：SD卡中专门存放当前应用缓存数据的位置，通过getExternalCacheDir()方法获得该目录
        //为什么要使用应用关联目录存放图片，android6.0开始读写SD卡被列为了危险权限，在其他目录下都需要运行时权限处理
        outputImage = new File(getActivity().getExternalCacheDir(),"output_image");
        try {
            if(outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //android7.0以上需要使用此方式，否则会抛出一个FileUriExposedException异常
        //原因：直接使用本地真实路径的Uri被认为式不安全的，使用FileProvider内容提供器可以对数据进行保护
        if(Build.VERSION.SDK_INT >=24){
            imageUri = FileProvider.getUriForFile(getActivity(),
                    "com.example.client_anna.fileprovider",outputImage);
        }else {
            imageUri = Uri.fromFile(outputImage);
        }

        //隐式启动Intent：系统会去找到可以响应这个Intent的活动启动，不是指明具体的跳转对象的
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        //图片输出路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,TAK_PHOTO);
    }

    //权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions,
                                           @NonNull @NotNull int[] grantResults) {
        switch (requestCode){
            case 1:
                //有无打开相册的权限判断
                if(grantResults.length > 0 && grantResults[0] == PackageManager.
                        PERMISSION_GRANTED){
                    go_album();
                }else {
                    Toast.makeText(getActivity(),"You denied the permission",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    private Bitmap explore_bitmap;
    //A当前活动
    //A跳转B，B回到A触发的事件
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.
            jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CHOOSE_PHOTO:
                //从手机相册中选择
                if(resultCode == getActivity().RESULT_OK){
                    if(Build.VERSION.SDK_INT>=19){
                        //4.4以上系统使用该方法获取图片
                        //原因：4.4版本开始选择手机相册中的图片不再返回图片真实的Uri，而是一个封装过的Uri
                        //所以需要使用该方法对其进行解析
                        handleImageOnKitKat(data);
                    }else {
                        handleImageBeforeKiKat(data);
                    }
                }
                break;
            case TAK_PHOTO:
                //调用手机相机拍照
                if(resultCode == getActivity().RESULT_OK){
                    try {
                        //ContentResolver接口:实现共享数据
                        //程序间的数据想要向外传递就可以使用该接口将数据完全暴露
                        ContentResolver contentResolver = getActivity().getContentResolver();
                        //获取openInputStream(imageUri)输入流中的数据，转换成bitmap
                        explore_bitmap = BitmapFactory.decodeStream(contentResolver.
                                openInputStream(imageUri));
                        //转换成file文件上传
                        file = outputImage;
                        if(file!=null){
                            Log.d(TAG,"file_我是相机拍照选择的图片");
                        }
                        if(explore_bitmap==null){
                            Toast.makeText(getActivity(),"添加图片失败",Toast.LENGTH_SHORT).
                                    show();
                        }else {
                            Message message = new Message();
                            message.what = 6;
                            handler.sendMessage(message);
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }

    }

    //4.4系统的手机调用该方法对封装的Uri进行解析
    private void handleImageOnKitKat(Intent data){
        String imagePath = null;
        Uri uri = data.getData();
        if(DocumentsContract.isDocumentUri(getActivity(),uri)){
            //如果是document类型的Uri，则通过document id 处理
            String dacId = DocumentsContract.getDocumentId(uri);
            //如果是media格式的Uri，需要对document id进一步解析
            //使用字符串分割的方式去除后半段部分得到真正的数字id，在用id构建出新的Uri和条件语句
            //之后传入getImagePath()方法中获取图片的真实路径
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = dacId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" +
                        "//downloads/public_downloads"),Long.valueOf(dacId));
                imagePath = getImagePath(contentUri,null);
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            //如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri,null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            //如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        //根据图片路径显示图片
        displayImage(imagePath);
    }

    private void handleImageBeforeKiKat(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }

    //获取图片路径
    private String getImagePath(Uri uri,String selection){
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getActivity().getContentResolver().query(uri,null,selection,
                null,null);
        if(cursor != null){
            if(cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private File file;
    //通过输入流方式转换图片，并显示在UI界面
    private void displayImage(String imagePath){
        if(imagePath != null){
            Log.d(TAG,imagePath);
            explore_bitmap = BitmapFactory.decodeFile(imagePath);
            if(explore_bitmap==null&&imagePath!=null){
                Log.e("手机相册调用从回收站恢复的图片","java.io.FileNotFoundException");
                Message message = new Message();
                message.what = 10;
                handler.sendMessage(message);
            }else {
                //绝对路径转换成文件形式，path转file
                file = new File(imagePath);
                if (file != null) {
                    Log.d(TAG, "file_我是从相册选择的图片");
                }
                Message message = new Message();
                message.what = 6;
                handler.sendMessage(message);
            }
        }else {
            Toast.makeText(getActivity(), "failed to get image",
                    Toast.LENGTH_SHORT);
        }
    }

    //Fragment页面加载时绘制UI界面
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        //防止资源浪费
        if(rootView==null){
            //为Fragment添加布局文件
            rootView = inflater.inflate(R.layout.activity_explore_fragment,container,
                    false);
            recyclerView = rootView.findViewById(R.id.recycler_view);
            //取消动画效果
            ((DefaultItemAnimator) recyclerView.getItemAnimator())
                    .setSupportsChangeAnimations(false);
            //不显示执行动画
            recyclerView.setItemAnimator(null);
            //传入Draw_本次网络请求为第一次绘制
            Explore_Okhttp3("Draw");
        }

        Log.d(TAG,"onCreateView ");
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.
            Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //实例化SmartRefreshLayout控件
        RefreshLayout refreshLayout = (RefreshLayout) getActivity().
                findViewById(R.id.refreshLayout);
        //SmartRefreshLayout事件回调方法
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                //传入Refresh_本次网络请求为刷新
                Explore_Okhttp3("Refresh");
                //上拉加载启用
                refreshLayout.setEnableLoadMore(true);
                //false表示启用上拉加载
                aBoolean=false;
                //数据刷新完结束事件
                refreshLayout.finishRefresh(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                //传入Load_本次网络请求为加载
                Explore_Okhttp3("Load");

                //true表示禁用下拉加载
                if(aBoolean==true){
                    //禁用下拉加载
                    refreshLayout.setEnableLoadMore(false);
                    Toast.makeText(getActivity(),"真的没有了",Toast.LENGTH_SHORT).show();
                }
                //数据刷新完结束事件
                refreshLayout.finishLoadMore(true);
            }
        });

        //实例化悬浮按钮
        FloatingActionButton fab = (FloatingActionButton) getActivity().
                findViewById(R.id.explore_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按钮点击触发的事件
                Message message = new Message();
                message.what=5;
                handler.sendMessage(message);
            }
        });

    }

    //Fragment页面加载时第一个执行的生命周期方法
    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.
            Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate ");
    }

    //第一次与活动产生联系时执行的方法
    @Override
    public void onAttach(@NonNull @NotNull Context context) {
        super.onAttach(context);
        Log.d(TAG,"onAttach ");
    }

}